package com.ws.universal.tools.takephoto.crop;


import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.bumptech.glide.Glide;
import com.ws.universal.tools.R;
import com.ws.universal.tools.utils.LogcatUtils;

import java.io.IOException;
import java.io.OutputStream;


/**
 * @author:ws
 * @date: 2020/9/1 16:46
 * @desc
 */
public class CropImageActivity extends MonitoredActivity {
    private final Handler handler = new Handler();
    private boolean saveAsPng;
    private Uri sourceUri;
    private boolean isChangeCropSize;
    private Uri saveUri;
    private CropImageView imageView;
    private int aspectX;//裁剪宽 默认单位dp
    private int aspectY;//裁剪高

    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setupViews();
        loadInput();
    }


    private void setupViews() {
        setContentView(R.layout.crop_activity_crop);
        imageView = findViewById(R.id.crop_image);

        findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setResult(0);
                finish();
            }
        });
        findViewById(R.id.btn_done).setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                onSaveClicked();
            }
        });
    }

    private void loadInput() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {

            saveAsPng = extras.getBoolean("as_png", false);
            isChangeCropSize = extras.getBoolean("isChangeCropSize", false);
            aspectX = extras.getInt("aspect_x", 200);
            aspectY = extras.getInt("aspect_y", 200);
            saveUri = (Uri) extras.getParcelable("output");
        }
        sourceUri = intent.getData();
        LogcatUtils.i(" sourceUri " + sourceUri.toString());
        imageView.setDrawable(aspectX, aspectY);
        imageView.setChangeCropSize(isChangeCropSize);
        Glide.with(this).load(sourceUri.toString()).into(imageView);

    }


    private void onSaveClicked() {
        saveImage(imageView.getCropImage());
    }

    private void saveImage(final Bitmap croppedImage) {
        if (croppedImage != null) {
            CropUtil.startBackgroundJob(this, (String) null, getResources().getString(R.string.crop__saving), new Runnable() {
                public void run() {
                    saveOutput(croppedImage);
                }
            }, handler);
        } else {
            finish();
        }
    }

    private void saveOutput(final Bitmap croppedImage) {
        if (saveUri != null) {
            OutputStream outputStream = null;

            try {
                outputStream = getContentResolver().openOutputStream(saveUri);
                if (outputStream != null) {
                    croppedImage.compress(saveAsPng ? CompressFormat.PNG : CompressFormat.JPEG, 90, outputStream);
                }
            } catch (IOException var7) {
                setResultException(var7);
                LogcatUtils.e("Cannot open file: " + saveUri, var7);
            } finally {
                CropUtil.closeSilently(outputStream);
            }
            CropUtil.copyExifRotation(CropUtil.getFromMediaUri(this, getContentResolver(), sourceUri), CropUtil.getFromMediaUri(this, getContentResolver(), saveUri));
            setResultUri(saveUri);
        }
        handler.post(new Runnable() {
            public void run() {
                croppedImage.recycle();
            }
        });
        finish();
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    public boolean onSearchRequested() {
        return false;
    }


    private void setResultUri(Uri uri) {
        setResult(-1, (new Intent()).putExtra("output", uri));
    }

    private void setResultException(Throwable throwable) {
        setResult(404, (new Intent()).putExtra("error", throwable));
    }
}
